#include <sw/redis++/redis++.h>
#include <iostream>
#include <string>
#include <vector>
using namespace sw::redis;

void RetryConnection(Redis &redis)
{
    std::string statu = redis.ping();
    int cnt = 5;
    while (statu != "PONG" && cnt)
    {
        --cnt;
        statu = redis.ping();
    }
    std::cout << "connection statu: " << statu << std::endl;
}
void unity1(Redis &redis)
{
    printf("开始执行hset和hget了\n");
    redis.flushall();
    StringView table_name = "user";
    long long n = redis.hset(table_name, std::make_pair("id", "{name: 张三\r\nage: 18\r\n}"));
    std::cout << "hset command res : " << n << std::endl;

    OptionalString res = redis.hget(table_name, "id");

    if (res.has_value())
        std::cout << "hget command res : " << res.value() << std::endl;
}

void unity2(Redis &redis)
{
    printf("开始执行hexists和hdel了\n");

    bool ret = redis.hexists("user", "id");
    std::cout << "hexists command res : " << ret << std::endl;

    long long n = redis.hdel("user", "id");
    std::cout << "hdel command res : " << n << std::endl;
}

void unity3(Redis &redis)
{
    printf("开始执行hkeys和hvals、Hlen、hgetall了\n");

    redis.hset("user", std::make_pair("statu", "OK"));

    std::vector<std::string> res;
    auto it = std::back_inserter(res);
    redis.hkeys("user", it);

    if (!res.empty())
    {
        for (auto &x : res)
        {
            std::cout << "key-->" << x << std::endl;
        }
        std::cout << "\n";
    }
    else std::cout << "user中没有key" << std::endl;

    printf("---------------------------\n");
    res.clear();
    it = std::back_inserter(res);
    redis.hvals("user", it);
    if (!res.empty())
    {
        for (auto &x : res)
        {
            std::cout << x << std::endl;
        }
        std::cout << "\n";
    }
    else  std::cout << "user中没有val" << std::endl;

    printf("---------------------------\n");

    int n = redis.hlen("user");
    std::cout << "hlen command res : " << n << std::endl;

    res.clear();
    it = std::back_inserter(res);
    redis.hgetall("user", it);

    if (!res.empty())
    {
        for (auto &x : res)
        {
            std::cout << x << std::endl;
        }
        std::cout << "\n";
    }
    else  std::cout << "user中没有key--val键值对" << std::endl;
}
int main()
{
    Redis redis("tcp://127.0.0.1:6379");
    RetryConnection(redis);
    // unity1(redis);
    // unity2(redis);
    // unity3(redis);
    return 0;
}